package com.kelp.codetoolkit.utils

import com.intellij.openapi.ui.Messages
import com.kelp.codetoolkit.constant.GlobalConfig
import org.apache.velocity.VelocityContext
import org.apache.velocity.app.VelocityEngine
import java.io.StringWriter

/**
 * @author: liuyuebai
 * @date: 2024/8/3 14:04
 * @description:
 */
object FileContentTemplateUtil {

    fun generateFileCodeContent(templateContent:String,params:MutableMap<String,Any>): String {
        // 每次创建一个新实例，防止velocity缓存宏定义
        val velocityEngine = VelocityEngine()
        val velocityContext = VelocityContext()
        if (!CollectionUtil.isEmpty(params)){
            params.forEach(velocityContext::put)
        }
        val writer = StringWriter()
        try {
            velocityEngine.evaluate(velocityContext, writer, "Velocity Code Generate", templateContent)
        }catch (e:Exception){
            Messages.showWarningDialog("The content of the template for creating business logic files is incorrect.",GlobalConfig.getCodeToolKitPanelTitle());
            return ""
        }
        var code = writer.toString()
        code = code.replace(Regex("\\r\\n|\\r"), "\n")
        val buffer = StringBuffer(code)
        while (buffer.isNotEmpty() && Character.isWhitespace(buffer.first())) {
            buffer.deleteCharAt(0)
        }
        return buffer.toString()
    }
}